package com.aproj.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.aproj.model.Role;
import com.aproj.model.User;
import com.aproj.service.UserLocalServiceUtil;

public class CustomAuthProvider implements AuthenticationProvider{

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		
		User user = UserLocalServiceUtil.Authenticate(authentication.getName(), authentication.getCredentials().toString());
		
		if(user !=null){
			
			List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
			for(Role role: user.getRoles()){
				authorities.add(new GrantedAuthorityImpl(role.toString()));
			}
			return new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials().toString(), authorities);
		}
		
		throw new BadCredentialsException("auth failed");
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

	

}
